<?php
define('SUB_DIR','/services');
$actions = array('custom_site','save_custom_site','get_site_comment','add_site_comment','site_handler','get_maps','jifen_exchange','goods_handler','get_city_sites','clear_goods','get_goods_comment','add_goods_comment');
if(isset($_REQUEST['action']))
{
	$action = strtolower($_REQUEST['action']);
	
	if(!in_array($action,$actions))
		exit;
}
else
	exit;

require '../core/service/fanwe.service.php';

if($action == 'get_maps')
{
	$fanwe = &FanweService::instance();
	$fanwe->is_group_city = false;
	$fanwe->is_session = false;
	$fanwe->is_user = false;
	$fanwe->is_cron = false;
	$fanwe->cache_list = array('goods');
	$fanwe->initialize();

	global $_FANWE;

	$min_lng = floatval($_FANWE['request']['min_lng']);
	$min_lat = floatval($_FANWE['request']['min_lat']);
	$max_lng = floatval($_FANWE['request']['max_lng']);
	$max_lat = floatval($_FANWE['request']['max_lat']);

	$cate = intval($_FANWE['request']['cate']);
	$sort = trim($_FANWE['request']['sort']);
	$page = intval($_FANWE['request']['page']);
	if($page == 0)
		$page = 1;

	$page_size = 26;

	$where = "";

	$sort_array = array("id"=>"g.id desc","bought"=>"g.bought desc");

	if(array_key_exists($sort,$sort_array))
	{
		$order= $sort_array[$sort];
	}
	else
		$order = "g.id desc";

	$order .= ",g.sort asc,g.end_time asc";

	if(abs($min_lng) > 0 && abs($min_lat) > 0 && abs($max_lng) > 0 && abs($max_lat) > 0)
	{
		$where .= "AND (longitude >= $min_lng and latitude >= $min_lat) and (longitude <= $max_lng and latitude <= $max_lat)";
	}
	else
	{
		$where .= "AND (longitude >= 116.23981475830076 and latitude >= 39.83885904487285) and (longitude <= 116.5762710571289 and latitude <= 39.97054256712116)";
	}

	$query = DB::query('SELECT DISTINCT goods_id FROM '.DB::table('suppliers')." WHERE goods_id > 0 $where");
	$id_array = array();
	while($id = DB::fetch($query))
	{
		$id_array[] = $id['goods_id'];
	}

	$ids = implode(",",$id_array);
	
	if($cate > 0)
	{
		$cateobj = $_FANWE['cache']['goods']['cats'][$cate];
		if(!empty($cateobj))
		{
			$cate_ids = array();
			if(isset($cateobj['childs']))
				$cate_ids = $cateobj['childs'];
			
			$cate_ids[] = $cate;
			
			if(count($cate_ids) > 1)
				$goods_where.=' AND gk.cate_id IN ('.implode(',', $cate_ids).')';
			else
				$goods_where.=" AND gk.cate_id = '$cate'";
		}
		else
		{
			$cate = 0;
			unset($page_args['cat']);
		}
	}

	$goods_count = 0;
	$goods_list = array();
	$supplier_list = array();
	$page_count = 0;

	if(!empty($ids))
    {
        $query = DB::query('SELECT gk.id FROM '.DB::table('goods_now_key')." AS gk WHERE gk.id IN ($ids) $goods_where GROUP BY gk.id ");
        $id_array = array();
        while($id = DB::fetch($query))
        {
            $id_array[] = $id['id'];
        }
        $goods_count = count($id_array);
        $ids = implode(",",$id_array);
    }

	if($goods_count > 0)
	{
		$page_count = ceil($goods_count/$page_size);

		if($page > $page_count)
			$page = $page_count;

		$limit = (($page - 1) * $page_size) + "," + $page_size;

		$query = DB::query('SELECT DISTINCT g.id,g.site_id,g.name,g.city,g.cate_id,g.url,g.click_count,g.best_count,g.collect_count,
				g.shop_price,g.market_price,g.end_time,g.small_img,g.score,g.bought,g.site_name,(g.shop_price / g.market_price) AS discount
				FROM '.DB::table('goods_now_key').' AS gk
				INNER JOIN '.DB::table('goods_now')." AS g ON g.id = gk.id
				WHERE gk.id IN ($ids) $goods_where ORDER BY $order LIMIT $limit");

		$goods_ids = array();

		while($goods = DB::fetch($query))
		{
			S('Goods')->goodsFormat($goods);

			if($goods['cate_id'] > 0)
			{
				$cate = $_FANWE['cache']['goods']['cats'][$goods['cate_id']];
				if($cate['pid'] > 0)
					$goods['cate_id'] = $cate['pid'];
			}

			$goods_ids[] = $goods['id'];
			$goods_list['g'.$goods['id']] = $goods;
		}

		$goods_ids = implode(",",$goods_ids);
	
		$query = DB::query('SELECT s.*,g.site_name FROM '.DB::table('suppliers')." AS s 
			INNER JOIN ".DB::table('goods_now')." AS g ON g.id = s.goods_id  
			WHERE s.goods_id IN ($goods_ids) $where");
		while($data = DB::fetch($query))
		{
			if(empty($data['name']))
				$data['name'] = $data['site_name'];
			$supplier_list[] = $data;
		}
	}

	$pages = array(
		'page'=>$page,
		'pageCount' => $page_count,
		'goodsCount' => $goods_count
	);

	$result = array("goodsList"=>$goods_list,"supplierList"=>$supplier_list,"pages"=>$pages);

	include import('class/json');
	$json = new JSON();
	die($json->encode($result));
}
elseif($action == 'jifen_exchange')
{
	$fanwe = &FanweService::instance();
	$fanwe->cache_list = array();
	$fanwe->initialize();
	
	$result = array('html'=>'','status'=>1,'msg'=>'');
	global $_FANWE;
	
	include import('class/json');
	$json = new JSON();
	
	$id = intval($_FANWE['request']['id']);
	
	if($id > 0)
	{
		$goods = S("JiFen")->getItem($id);
	}
	
	if($_FANWE['uid'] > 0 && $goods)
	{
		$score = S("User")->getUserScore();
		if($score < $goods['integral'])
		{
			$result['status'] = 0;
			$result['msg'] = lang('jifen','integral_error');
			die($json->encode($result));
			exit;
		}
		
		if($goods['stock'] <= intval($goods['exchange_count']))
		{
			$result['status'] = 0;
			$result['msg'] = lang('jifen','stock_error');
			die($json->encode($result));
			exit;
		}
		
		$data['zip'] = trim($_FANWE['request']['zip']);
		$data['address'] = trim($_FANWE['request']['address']);
		$data['email'] = trim($_FANWE['request']['email']);
		$data['mobile_phone'] = trim($_FANWE['request']['mobilePhone']);
		$data['fax_phone'] = trim($_FANWE['request']['faxPhone']);
		$data['fix_phone'] = trim($_FANWE['request']['fixPhone']);
		$data['qq'] = trim($_FANWE['request']['qq']);
		
		$consignment = $data;
		$consignment['id'] = $_FANWE['uid'];
		
		if(!empty($consignment['address']))
		{
			DB::insert('user_consignee',$consignment,false,true);
		}
		
		$data['memo'] = trim($_REQUEST['memo']);
		
		if(empty($goods['name']))
			$data['data_name'] = $goods['goods_name'];
		else
			$data['data_name'] = $goods['name'];
			
		$data['sn'] = toDate(gmtTime(),'ymdHis').mt_rand(0,100);
		$data['goods_status'] = 0;
		$data['order_score'] = $goods['integral'];
		$data['data_num'] = 1;
		$data['user_id'] = $_FANWE['uid'];
		$data['user_name'] = $_FANWE['user']['user_name'];
		$data['rec_id'] = $id;
		$data['create_time'] = TIME_UTC;
		$data['update_time'] = TIME_UTC;
		
		
		$order_id = DB::insert('order',$data,true);
		
		while(intval($order_id)==0)
		{
			$order['sn'] = toDate(gmtTime(),'ymdHis').mt_rand(0,100);
			$order_id = DB::insert('order',$data,true);
		}
		
		$msg = sprintf(lang('user','jifen_exchang_score'),$data['data_name']);
		
		S("User")->updateUserScore($_FANWE['uid'],"jifen","exchange",$msg,$order_id,0 - intval($data['order_score']));
		
		if($goods['goods_type'] == 0)
		{
			$bond = DB::fetchFirst('SELECT * FROM '.DB::table('goods_bond').' WHERE goods_id = '.$goods['goods_id'].' AND status = 1 AND order_sn = \'\' AND user_id = 0');

			if($bond)
			{
				$adm_memo  = lang('jifen','bond_sn').'：'.$bond['sn'];
				if(!empty($bond['password']))
				{
					$adm_memo.='<br/>'.lang('jifen','bond_pwd').'：'.$bond['password'];
				}
				
				if(DB::update('order',array(
								'goods_status'=>1,
								'adm_memo'=>$adm_memo
							),"id = $order_id"))
				{
					
					$bond['order_sn'] = $data['sn'];
					$bond['send_time'] = TIME_UTC;
					$bond['user_id'] = $data['user_id'];
					DB::insert('goods_bond',$bond,false,true);
				}
			}
		}
		
		$result['msg'] = lang('jifen','jifen_success');
	}
	else
	{
		if($_FANWE['uid'] == 0)
		{
			$result['status'] = 0;
			$result['msg'] = lang('jifen','user_error');
		}
		else
		{
			$result['status'] = 0;
			$result['msg'] = lang('jifen','goods_error');
		}
	}

	die($json->encode($result));
	exit;
}
elseif($action == 'custom_site')
{
	$fanwe = &FanweService::instance();
	$fanwe->is_group_city = true;
	$fanwe->cache_list = array('site','city');
	$fanwe->initialize();
	loadCache('city_site_'.CURRENT_CITY_PY);
	global $_FANWE;
	
	$city_name = $_FANWE['current_city']['name'];

	$cache_args = array(
		'custom_site',
		CURRENT_CITY_PY
	);
	
	$cache_file = getTplCache('inc/ajax/select_site',$cache_args);
	
	$is_custom_site = true;

	if(!@include($cache_file))
		include template('inc/ajax/select_site');
	
	display($cache_file);
}
elseif($action == 'goods_handler')
{
	$fanwe = &FanweService::instance();
	$fanwe->cache_list = array();
	$fanwe->initialize();
	
	$result = array('html'=>'','status'=>1,'msg'=>'');
	
	if($_FANWE['uid'] == 0)
	{
		$result['status'] = 3;
	}
	elseif($_FANWE['group_id'] == 2)
	{
		$result['status'] = 4;
	}
	else
	{
		$goods_id =  intval($_FANWE['request']['goods_id']);
		$type = trim($_FANWE['request']['type']);
		$types = array('GOODS_COLLECT','GOODS_BEST');
		
		if(in_array($type,$types) && $goods_id > 0)
		{
			$check = DB::resultFirst('SELECT COUNT(id) FROM '.DB::table('goods').' 
										WHERE id = '.$goods_id.' AND status = 1');
			if(intval($check) > 0)
			{
				$data['user_id'] = $_FANWE['uid'];
				$data['add_time'] = TIME_UTC;
				$data['rec_id'] = $goods_id;
				$data['num'] = 1;
				$data['type'] = $type;
				$data['ip'] = $_FANWE['client_ip'];
				
				if($type == "GOODS_BEST")
				{
					$cnow = TIME_UTC - 3600;
					
					$check = DB::resultFirst('SELECT COUNT(*) FROM '.DB::table('rank').' WHERE rec_id = '.$goods_id."
											 AND type = '$type' AND user_id = '$_FANWE[uid]' AND add_time > $cnow");
										
					if(intval($check) > 0)
					{
						$result['status'] = 2;
					}
					else
					{
						DB::insert('rank',$data);
						S('RankStatistic')->goods($goods_id,'GOODS_BEST');
						$result['status'] = 1;
					}
				}
				elseif($type == "GOODS_COLLECT")
				{
					$check = DB::resultFirst('SELECT COUNT(*) FROM '.DB::table('user_goods').' WHERE 
												goods_id = '.$goods_id." AND user_id = $_FANWE[uid]");			 
					if(intval($check) > 0)
					{
						$result['status'] = 2;
					}
					else
					{
						S('RankStatistic')->goods($goods_id,'GOODS_COLLECT');
						$result['status'] = 1;
						$ug['user_id'] = $_FANWE['uid'];
						$ug['goods_id'] = $goods_id;
						DB::insert('user_goods',$ug);
					}
				}
			}
		}
	}
	
	include import('class/json');
	$json = new JSON();
	die($json->encode($result));
}
elseif($action == 'site_handler')
{
	$fanwe = &FanweService::instance();
	$fanwe->cache_list = array();
	$fanwe->initialize();
	
	$result = array('html'=>'','status'=>1,'msg'=>'');
	
	if($_FANWE['uid'] == 0)
	{
		$result['status'] = 3;
	}
	elseif($_FANWE['group_id'] == 2)
	{
		$result['status'] = 4;
	}
	else
	{
		$site_id =  intval($_FANWE['request']['site_id']);
		$type = trim($_FANWE['request']['type']);
		$types = array('SITE_BEST','SITE_CUSTOM');
		
		if(in_array($type,$types) && $site_id > 0)
		{
			$check = DB::resultFirst('SELECT COUNT(id) FROM '.DB::table('site').' 
										WHERE id = '.$site_id.' AND status = 1');
			if(intval($check) > 0)
			{
				$data['user_id'] = $_FANWE['uid'];
				$data['add_time'] = TIME_UTC;
				$data['rec_id'] = $site_id;
				$data['num'] = 1;
				$data['type'] = $type;
				$data['ip'] = $_FANWE['client_ip'];
				
				if($type == "SITE_BEST")
				{
					$cnow = TIME_UTC - 3600;
					
					$check = DB::resultFirst('SELECT COUNT(*) FROM '.DB::table('rank').' WHERE rec_id = '.$site_id."
											 AND type = '$type' AND user_id = '$_FANWE[uid]' AND add_time > $cnow");
										
					if(intval($check) > 0)
					{
						$result['status'] = 2;
					}
					else
					{
						DB::insert('rank',$data);
						S('RankStatistic')->site($site_id,'SITE_BEST');
						$result['status'] = 1;
					}
				}
				elseif($type == "SITE_CUSTOM")
				{
					$check = DB::resultFirst('SELECT COUNT(*) FROM '.DB::table('user_site').' WHERE 
												site_id = '.$site_id." AND user_id = $_FANWE[uid]");
											 
					if(intval($check) > 0)
					{
						$result['status'] = 2;
					}
					else
					{
						S('RankStatistic')->site($site_id,'SITE_CUSTOM');
						
						$result['status'] = 1;
						$custom['user_id'] = $_FANWE['uid'];
						$custom['site_id'] = $site_id;
						DB::insert('user_site',$custom);
					}
				}	
			}
		}
	}
	
	include import('class/json');
	$json = new JSON();
	die($json->encode($result));
}
elseif($action == 'save_custom_site')
{
	$fanwe = &FanweService::instance();
	$fanwe->cache_list = array();
	$fanwe->initialize();
	
	if($fanwe->var['uid'] > 0)
		S('User')->updateCustomSite($fanwe->var['request']['site_ids']);
}
elseif($action == 'get_site_comment')
{
	$fanwe = &FanweService::instance();
	$fanwe->cache_list = array();
	$fanwe->initialize();
	
	$filter = $_FANWE['request']['filter'];
	if(intval($filter['rec_id']) == 0)
		return false;
	
	include import('function/page');
	
	$filter['recordCount'] = S('Message')->getMessageCount('SiteMessage',intval($filter['rec_id']));
	$filter = pageAndSize($filter);
	$filter['pageNumber'] = getPageNumList($filter['page'],$filter['pageCount']);
	$limit = $filter['start'] . "," . $filter['pageSize'];
	
	$message_list = S('Message')->getMessageList('SiteMessage',intval($filter['rec_id']),$limit);
	
	include template('inc/ajax/site_comment');
	$html = display('',true);
	
	$site_score = DB::resultFirst('SELECT score FROM '.DB::table('site').' WHERE id = '.$filter['rec_id']);
	
	$result = array("html"=>$html,"filter" => $filter,"pageCount"=>$filter['pageCount'],'score'=>$site_score);
	include import('class/json');
	$json = new JSON();
	die($json->encode($result));
}
elseif($action == 'add_site_comment')
{
	$fanwe = &FanweService::instance();
	$fanwe->cache_list = array();
	$fanwe->initialize();
	global $_FANWE;
	
	$result = array('html'=>'','status'=>1,'msg'=>'');
	
	$rec_id = intval($_FANWE['request']['rec_id']);
		
	if($_FANWE['uid'] == 0)
	{
		$result['status'] = 0;
		$result['msg'] = '请先 登陆 或 注册！';
	}
	
	if($_FANWE['group_id'] == 2)
	{
		$result['status'] = 0;
		$result['msg'] = '团购网站主会员不能参加站点评论';
	}
	
	if($rec_id == 0 || $_FANWE['request']['content'] == '')
	{
		$result['status'] = 0;
		$result['msg'] = '非法提交！';
	}
	
	if($result['status'] == 1)
	{
		if(checkIpOperation("site_message",$_FANWE['setting']["message_inteval"],$rec_id))
		{
			$score = intval($_FANWE['request']['score']);
			$data['user_name'] = $_FANWE['user_name'];
			$data['title'] = strip_tags($_FANWE['request']['content']);
			$data['content'] = strip_tags($_FANWE['request']['content']);
			$data['user_id'] = $_FANWE['uid'];
			$data['rec_id'] = $rec_id;
			$data['score'] = $score > 5 ? 1 : $score;
			$data['rec_module'] = 'SiteMessage';
			$data['status'] = 1;
			$data['create_time'] = TIME_UTC;
			$data['update_time'] = TIME_UTC;
			
			if(DB::insert('message',$data))
			{
				S("RankStatistic")->site($rec_id,'SITE_SCORE');
				$msg = sprintf(lang('user','user_site_comment_score'),$_FANWE['request']['rec_name']);
				S("User")->updateUserScore($_FANWE['uid'],'site','comment',$rec_id,0,$msg);
			}
			else
			{
				$result['status'] = 0;
				$result['msg'] = '添加失败评论，请联系管理员或重新提交评论！';
			}
		}
		else
		{
			$result['status'] = 0;
			$result['msg'] = '你提交得太频繁了，请稍候再进行此站点的评论！';
		}
	}
	
	include import('class/json');
	$json = new JSON();
	die($json->encode($result));
}
elseif($action == 'get_goods_comment')
{
	$fanwe = &FanweService::instance();
	$fanwe->cache_list = array();
	$fanwe->initialize();
	
	$filter = $_FANWE['request']['filter'];
	if(intval($filter['rec_id']) == 0)
		return false;
	
	include import('function/page');
	
	$filter['recordCount'] = S('Message')->getMessageCount('Goods',intval($filter['rec_id']));
	$filter = pageAndSize($filter);
	$filter['pageNumber'] = getPageNumList($filter['page'],$filter['pageCount']);
	$limit = $filter['start'] . "," . $filter['pageSize'];
	
	$message_list = S('Message')->getMessageList('Goods',intval($filter['rec_id']),$limit);
	
	include template('inc/ajax/goods_comment');
	$html = display('',true);
	
	$result = array("html"=>$html,"filter" => $filter,"pageCount"=>$filter['pageCount']);
	include import('class/json');
	$json = new JSON();
	die($json->encode($result));
}
elseif($action == 'add_goods_comment')
{
	$fanwe = &FanweService::instance();
	$fanwe->cache_list = array();
	$fanwe->initialize();
	global $_FANWE;
	
	$result = array('html'=>'','status'=>1,'msg'=>'');
	
	$rec_id = intval($_FANWE['request']['rec_id']);
		
	if($_FANWE['uid'] == 0)
	{
		$result['status'] = 0;
		$result['msg'] = '请先 登陆 或 注册！';
	}
	
	if($_FANWE['group_id'] == 2)
	{
		$result['status'] = 0;
		$result['msg'] = '团购网站主会员不能参加商品评论';
	}
	
	if($rec_id == 0 || $_FANWE['request']['content'] == '')
	{
		$result['status'] = 0;
		$result['msg'] = '非法提交！';
	}
	
	if($result['status'] == 1)
	{
		if(checkIpOperation("goods_message",$_FANWE['setting']["message_inteval"],$rec_id))
		{
			$data['user_name'] = $_FANWE['user_name'];
			$data['title'] = strip_tags($_FANWE['request']['content']);
			$data['content'] = strip_tags($_FANWE['request']['content']);
			$data['user_id'] = $_FANWE['uid'];
			$data['rec_id'] = $rec_id;
			$data['score'] = 0;
			$data['rec_module'] = 'Goods';
			$data['status'] = 1;
			$data['create_time'] = TIME_UTC;
			$data['update_time'] = TIME_UTC;
			
			if(DB::insert('message',$data))
			{
				DB::query('UPDATE '.DB::table('goods')." SET post_count = post_count + 1 WHERE id = $rec_id");
				DB::query('UPDATE '.DB::table('goods_now')." SET post_count = post_count + 1 WHERE id = $rec_id");
				$msg = sprintf(lang('user','user_goods_comment_score'),$_FANWE['request']['rec_name']);
				S("User")->updateUserScore($_FANWE['uid'],'goods','comment',$rec_id,0,$msg);
			}
			else
			{
				$result['status'] = 0;
				$result['msg'] = '添加失败评论，请联系管理员或重新提交评论！';
			}
		}
		else
		{
			$result['status'] = 0;
			$result['msg'] = '你提交得太频繁了，请稍候再进行此商品的评论！';
		}
	}
	
	include import('class/json');
	$json = new JSON();
	die($json->encode($result));
}
elseif($action == 'get_city_sites')
{
	$fanwe = &FanweService::instance();
	$fanwe->cache_list = array('site','city');
	$fanwe->is_memory = false;
	$fanwe->is_session = false;
	$fanwe->is_user = false;
	$fanwe->is_cron = false;
	$fanwe->initialize();
	
	global $_FANWE;
	
	$city_py = $_FANWE['request']['city_py'];
	
	loadCache('city_site_'.$city_py);

	$html = '';
	
	if(isset($_FANWE['cache']['city']['all'][$city_py]))
	{
		$cache_args = array(
			$city_py,
		);
		
		$cache_file = getTplCache('inc/ajax/city_sites',$cache_args);
		if(!@include($cache_file))
		{
			$city = $_FANWE['cache']['city']['all'][$city_py];
			include template('inc/ajax/city_sites');
		}
		
		$html = display($cache_file,true);
	}
	
	die($html);
}
elseif($action == 'clear_goods')
{
	define('ROOT_PATH', str_replace('services/corn.php', '', str_replace('\\', '/', __FILE__)));
	clearDir(ROOT_PATH.'./public/tpl/caches/page_index_index');
}
?>